<template>
  <view class="container">
    <view class="header">
      <view class="title">{{ state.current_question + 1 }}/{{ props.list.length }}</view>
      <view class="has-done" v-if="loadover() == true">
        <text class="has-done-green" v-if="!hasDoQuestionListId.includes(props.list[state.current_question].id)">
          （未做）
        </text>
        <text class="has-done-gray" v-else>（已做）</text>
      </view>

      <view>
        <uni-icons v-if="has_collected() === false" @click="onClickCollectWrongQuestion(state.current_question)"
          type="star" size="30" class="button-item">
        </uni-icons>
        <uni-icons @click="onClickUnCollectWrongQuestion(state.current_question)" type="star-filled" size="30"
          class="button-item" v-else>
        </uni-icons>
      </view>
    </view>
    <view class="main">
      <swiper :indicator-dots="true" :autoplay="false" @change="onChangeSwiper" class="swiper">
        <swiper-item v-for="(question, index) in props.list" :key="index" class="swiper-item">
          <view>
            <text class="general_text">（{{ question.type_cn }}）</text>
          </view>
          <view @tap="onTapViewDetail(index)">
            <rich-text space="nbsp" :nodes="question.content_front_no_option" class="rich-text"></rich-text>
          </view>
          <view class="choice-item" v-for="(option_item, option_index) in question.option_list" :key="option_index"
            @tap="onTapChoiceOption(option_item, question.answer, option_index)"
            :class="{ 'active': state.isActiveList[option_index] }">
            <rich-text space="nbsp" :nodes="option_item" class="rich-text"></rich-text>
          </view>

          <view>
            <text class="rich-text">【作答结果】</text>
            <text :style="{ color: doChoiceQuestionResult === '正确' ? '#00ff00' : '#ff0000' }">
              {{ doChoiceQuestionResult }}
            </text>
          </view>
          <view v-if="question.type === 3">
            <button type="primary" size="mini" @click="onClickButton(question.answer)"
              :disabled="state.buttonEnabled">确定</button>
          </view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script setup lang="ts">
// 定义 props 接收数据
const props = defineProps<{
  list: QuestionItem[]
}>()
import { ref, reactive, computed } from 'vue'
import type { QuestionItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import UniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'
import { useDetailStore } from '@/stores'
import { postHasDoQuestionAPI, getHasDoQuestionAPI } from '@/services/home'
// import uniSwiperDot from '@dcloudio/uni-ui/lib/uni-swiper-dot/uni-swiper-dot.vue'
import {
  getAllWrongQuestionIdAPI,
  postCollectWrongQuestionAPI,
  postUnCollectWrongQuestionAPI,
} from '@/services/home'
// 做选择题的作答结果
const doChoiceQuestionResult = ref<string>('')
// 试题答案解析详情缓存
const detailStore = useDetailStore()
// 已做题目列表，用于后台发送阅读题目扣款，已做题目不扣款
const selectChoiceIndex = ref<number>(-1)
// 从服务器获取本人已做的题目列表
const hasDoQuestionListId = ref<number[]>([])

const optionStyles = ref<object>({ backgroundColor: '#ffffff' })
// 错题列表，用于显示是否需要收藏错题
const wrongQuestionList = ref<number[]>([])
// 把索引号转换成对应的选项字母
const convertInt2Char: string[] = ['A', 'B', 'C', 'D']
// 存放响应式变量
const state = reactive({
  current_question: 0,
  multiSelectList: ['', '', '', ''],
  isActiveList: [false, false, false, false],
  buttonEnabled: true,
})

// 适配宽和高，有一者查过250px，则相应的调整比例
const adaptWidthHeight = (width_str: string, height_str: string) => {
  let width = parseInt(width_str.slice(0, width_str.length - 2))
  let height = parseInt(height_str.slice(0, height_str.length - 2))
  const maxPx: number = 300
  if (width <= maxPx && height <= maxPx) {
    return 'width: ' + width_str + ';' + 'height: ' + height_str + ';'
  } else if (width > maxPx && height <= maxPx) {
    let width_new: number = maxPx
    let height_new: number = (height * width_new) / width
    return 'width: ' + width_new.toString() + 'px;' + 'height: ' + height_new.toString() + 'px;'
  } else if (width <= maxPx && height > maxPx) {
    let height_new: number = maxPx
    let width_new: number = (width * height_new) / height
    return 'width: ' + width_new.toString() + 'px;' + 'height: ' + height_new.toString() + 'px;'
  } else {
    if (width > height) {
      let width_new: number = maxPx
      let height_new: number = (height * width_new) / width
      return 'width: ' + width_new.toString() + 'px;' + 'height: ' + height_new.toString() + 'px;'
    } else {
      let height_new: number = maxPx
      let width_new: number = (width * height_new) / height
      return 'width: ' + width_new.toString() + 'px;' + 'height: ' + height_new.toString() + 'px;'
    }
  }
}
const loadover = () => {
  if (wrongQuestionList.value.length > 0 && props.list.length > 0) {
    return true
  } else {
    return false
  }
}
// 是否收藏过该题，计算属性
const has_collected = () => {
  // console.log('所有题目list，判断是否收藏过', props.list)
  let result = false
  if (props.list.length > 0) {
    result = wrongQuestionList.value.includes(props.list[state.current_question].id)
  }
  // console.log('收藏结果结果', result)
  return result
}
// 判断选项与答案是否一致
const judgeOptionWithAnswer = (selectOptionItem: string, answer: string, index: number) => {
  let selectChar = selectOptionItem.slice(selectOptionItem.indexOf('.') - 1, 1)
  let answerSplit = answer.replace(/^\s+|\s+$/g, '')
  if (selectChar === answerSplit && index === selectChoiceIndex.value) {
    optionStyles.value = { backgroundColor: '#00ff00' }
  } else if (selectChar !== answerSplit && index === selectChoiceIndex.value) {
    optionStyles.value = { backgroundColor: '#ff0000' }
  } else {
    optionStyles.value = { backgroundColor: '#ffffff' }
  }
}
// 多选题的按钮提交答案
const onClickButton = (answer: string) => {
  let answerSplit = answer.replace(/^\s+|\s+$/g, '')
  answerSplit = answerSplit.replace(/<\/?p[^>]*>/g, '')
  answerSplit = answerSplit.trim()
  let selectChar = state.multiSelectList.join('')
  selectChar = selectChar.trim()
  if (selectChar === answerSplit) {
    doChoiceQuestionResult.value = '正确'
  } else {
    doChoiceQuestionResult.value = '错误'
  }
  let question: QuestionItem = props.list[state.current_question]
  if (!hasDoQuestionListId.value.includes(question.id)) {
    console.log('本题没做过，发送后端创建')
    postHasDoQuestion(question.id)
  } else {
    console.log('该题目已做过，没必要提交创建已读题目')
  }
}
// 选择选项后的显示作答结果
const onTapChoiceOption = (selectOptionItem: string, answer: string, index: number) => {
  // 让按钮可用
  if (props.list[state.current_question].type == 3) {
    state.buttonEnabled = false
  }
  // 获取当前正在答题的试题
  let question: QuestionItem = props.list[state.current_question]
  // 单选题或者判断题，单击某个选项后，其他选项的选中都清空
  if (question.type == 1 || question.type == 4) {
    for (let i = 0; i < state.isActiveList.length; i++) {
      state.isActiveList[i] = false
    }
  }
  state.isActiveList[index] = !state.isActiveList[index]
  let selectChar: string = ''
  if (question.type == 1 || question.type == 4) {
    selectChar = selectOptionItem.slice(selectOptionItem.indexOf('.') - 1, 1)
  } else {
    let char_temp: string = state.multiSelectList[index]
    if (char_temp === '') {
      state.multiSelectList[index] = convertInt2Char[index]
    } else {
      state.multiSelectList[index] = ''
    }
    console.log('多选题，将退出')
    return 0
  }
  selectChoiceIndex.value = index
  let answerSplit = answer.replace(/^\s+|\s+$/g, '')
  answerSplit = answerSplit.replace(/<\/?p[^>]*>/g, '')
  selectChar = selectChar.trim()
  answerSplit = answerSplit.trim()
  if (selectChar === answerSplit) {
    doChoiceQuestionResult.value = '正确'
  } else {
    doChoiceQuestionResult.value = '错误'
  }
  if (!hasDoQuestionListId.value.includes(question.id)) {
    console.log('本题没做过，发送后端创建')
    postHasDoQuestion(question.id)
  } else {
    console.log('该题目已做过，没必要提交创建已读题目')
  }
  // judgeOptionWithAnswer(selectOptionItem, answer, index)
}
// 获取当前选中知识点下的题目列表，筛选已做题目类型
const getWrongQuestionIdData = async () => {
  const res = await getAllWrongQuestionIdAPI()
  console.log('所有错题id', res)
  if (res.code == 200) {
    wrongQuestionList.value = res.data.results
    console.log('获取错题成功questionList：', wrongQuestionList.value)
  } else {
    uni.showToast({ icon: 'error', title: '获取错题失败' })
  }
}
// 提交已经做题记录，后端创建做题记录，并扣款
const postHasDoQuestion = async (question: number) => {
  let param_data = { question: question }
  const res = await postHasDoQuestionAPI(param_data)
  console.log('提交已做题目结果', res)
  if (res.code == 200) {
    // 更新已做题目id列表
    hasDoQuestionListId.value = res.data.results
    console.log('提交已做题目成功', hasDoQuestionListId.value)
  } else if (res.code == 500) {
    uni.showToast({ icon: 'error', title: '服务器错误！' })
  } else {
    console.log('提交已做题目失败')
  }
}
// 获取已读题目列表，用于判断是否需要发送后端请求创建已读记录
const getHasDoQuestion = async () => {
  const res = await getHasDoQuestionAPI()
  console.log('提交已做题目结果', res)
  if (res.code == 200) {
    hasDoQuestionListId.value = res.data.results
    console.log('读取已做题目成功', hasDoQuestionListId.value)
  } else if (res.code == 500) {
    uni.showToast({ icon: 'error', title: '服务器错误！' })
  } else {
    console.log('读取已做题目失败')
  }
}
// 查看题目详情
const onTapViewDetail = (index: number) => {
  console.log('查看的题目是', props.list[index])
  let question: QuestionItem = props.list[index]
  detailStore.setDetail(question)
  if (!hasDoQuestionListId.value.includes(question.id)) {
    console.log('本题没做过，发送后端创建')
    postHasDoQuestion(question.id)
  } else {
    console.log('该题目已做过，没必要提交创建已读题目')
  }
  uni.navigateTo({ url: '/pages/compose/detail' })
}
// 滑动页改编
const onChangeSwiper = (e: any) => {
  // console.log('改动了：', e)
  state.current_question = e.detail.current
  selectChoiceIndex.value = -1
  doChoiceQuestionResult.value = ''
  state.isActiveList = [false, false, false, false]
}
// 收藏错题
const onClickCollectWrongQuestion = async (current_index: number) => {
  let question_id = props.list[current_index].id
  const res = await postCollectWrongQuestionAPI({ question_id: question_id })
  console.log('提交收藏错题后，', res)
  if (res.code == 200) {
    uni.showToast({ icon: 'success', title: '提交错题成功' })
    wrongQuestionList.value = res.data.results
  } else {
    uni.showToast({ icon: 'error', title: '提交错题失败' })
  }
}
// 取消收藏错题
const onClickUnCollectWrongQuestion = async (current_index: number) => {
  let question_id = props.list[current_index].id
  const res = await postUnCollectWrongQuestionAPI({ question_id: question_id })
  console.log('取消错题后，', res)
  if (res.code == 200) {
    uni.showToast({ icon: 'success', title: '取消错题成功' })
    wrongQuestionList.value = res.data.results
  } else {
    uni.showToast({ icon: 'error', title: '取消错题失败' })
  }
}
// 页面加载
onLoad(() => {
  console.log('Myswiper的数据列表', props.list)
  getWrongQuestionIdData()
  getHasDoQuestion()
  selectChoiceIndex.value = -1
})
</script>

<style lang="scss">
.container {
  margin: 5rpx;
  padding: 2rpx;
  // background-color: #ccecc6;
}

.header {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;
}

.general_text {
  color: chartreuse;
  font-size: 29rpx;
}

.has-done {
  display: flex;
  flex-flow: column warp;

  .has-done-green {
    color: green;
    font-size: 30rpx;
  }

  .has-done-gray {
    color: gray;
    font-size: 30rpx;
  }
}

.main {
  // height: 70vh;
  opacity: 0.5;
}

.title {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  padding: 8rpx;
  margin: 4rpx;
  width: 500rpx;
  font-size: 30rpx;
}

/* 清楚swiper默认高度 */
swiper {
  width: 750rpx;
  height: 90vh;
  padding: 5rpx;
}

.swiper-item {
  display: flex;
  flex-flow: column nowrap;
  justify-content: left;
  align-items: flex-start;
  // height: 150px;
  background-color: #ffffff;
  box-sizing: border-box;
  overflow: auto;
}

.button-item {
  margin: 30rpx;
}

.rich-text {
  font-size: 32rpx;
}

.two-button {
  width: 500rpx;
  margin: 30rpx;
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-end;
  align-items: center;
}

.choice-item {
  padding: 10px;
  border-radius: 5px;
  font-size: 30rpx;
  color: black;
  /* 背景颜色变深变亮的过渡效果 */
  transition: background-color 0.3s;

  // 当元素具有 .active 类时，背景颜色变为红色
  &.active {
    background-color: rgb(157, 255, 157);
  }

}

.text {
  font-size: 30rxp;
}
</style>
